package com.ll.mybatis;


import com.ll.mybatis.entity.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 刘龙
 * @version 1.0
 */
public class MybatisXML {

    public SqlSessionFactory getsqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }


    /**
     * 1.根据xml配置文件(全局配置文件 mybatis-config.xml) 创建一个SqlSessionFactory对象
     *      有数据源等一些运行环境信息
     * 2.sql映射文件(EmployeeMapper.xml):配置了每一个sql, 以及sql的封装规则等
     *
     * 步骤:
     *      1.根据全局配置文件得到SqlSessionFactory
     *      2.使用SqlSessionFactory得到SqlSession对象,用SqlSession对象来执行增删改查
     *      3.一个sqlSession就是代表和数据库的一次会话,用完关闭
     */

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {


        //2.获取sqlSession实例,能直接执行已经映射的sql语句
        SqlSession sqlSession = getsqlSessionFactory().openSession();

        try {
            /*
            *   <select id="selectEmp" resultType="com.ll.mybatis.entity.Employee">
                    select id, last_name, email, gender  from tbl_employee where id = #{id}
                </select>
            * */
            Employee employee2 = sqlSession.selectOne("com.ll.mybatis.dao.EmployeeMapper.selectEmp", 1);

            System.out.println(employee2);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 添加员工
     */
    @Test
    public void insertEmp() throws IOException {
        SqlSessionFactory sqlSessionFactory = getsqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();

        Employee employee = new Employee();
        employee.setLastname("赵六");
        employee.setGender("0");
        employee.setEmail("赵六@163.com");

        try {
            int insert = sqlSession.insert("com.ll.mybatis.dao.EmployeeMapper.addEmp", employee);

            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }


}
